import Taro from '@tarojs/taro'
import { HTTP_STATUS } from '@/constants/status'
import BASE_URL from '@/config'

type OptionType = {
  contentType?: string,
  url: string,
  data?: Record<string, any>,
  method?: any,
  header?: Record<string, any>,
  // mode: string,
  success?: (result: Taro.request.SuccessCallbackResult<any>) => void,
  error?: (err: any) => void,
  xhrFields?: Record<string, any>,
}

export default {
  baseOptions(params: OptionType, method = 'GET'): Taro.RequestTask<any> {
    const { url, data } = params;
    let contentType = 'application/json';
    contentType = params.contentType || contentType;

    const contentTypeObj = { 'content-type': contentType };
    //如果有传入header则合并成一个新header
    const header = params.header ? Object.assign(params.header, contentTypeObj) : contentTypeObj;

    const option: OptionType = {
      url: url.indexOf('http') !== -1 ? url : BASE_URL + url,
      data,
      method,
      header,
      // mode: 'cors',
      xhrFields: { withCredentials: true },
      success(res: any) {
        if (res.statusCode === HTTP_STATUS.SUCCESS) {
          return res.data;
        } else {
          let errMsg = "";
          if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
            errMsg = "请求资源不存在";
            return;
          } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
            errMsg = "服务端出现了问题"
            return;
          } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
            errMsg = "没有权限访问"
            return;
          } else if (res.statusCode === HTTP_STATUS.UNAUTHORIZED) {
            errMsg = "请先登录"
            Taro.clearStorage()
            // Taro.navigateTo({
            //   url: '/pages/login/index'
            // })
            return;
          } else if (res.statusCode === HTTP_STATUS.SERVER_ERROR) {
            errMsg = "服务器错误";
          }
          throw new Error(errMsg);
        }
      },
      error(e: any) {
        throw new Error(e);
      }
    }
    return Taro.request(option)
  },

  get(params: OptionType): Taro.RequestTask<any> {
    return this.baseOptions(params);
  },

  post(params: OptionType): Taro.RequestTask<any> {
    return this.baseOptions(params, 'POST');
  },

  put(params: OptionType): Taro.RequestTask<any> {
    return this.baseOptions(params, 'PUT');
  },

  delete(params: OptionType): Taro.RequestTask<any> {
    return this.baseOptions(params, 'DELETE');
  }
}


